const {getUserInfo} = require("../service/user.service")
const {userFormatterError,userAlreadyExist} = require("../constant/err.type")
const {userNoExist,userPasswordFalse,TokenExpiredError,JsonWebTokenError} = require("../constant/err.type")

const bcrypt = require("bcryptjs")
const UserValidate = async(ctx,next)=>{
    const {username,password} = ctx.request.body;
    if(!username||!password) {
        ctx.app.emit("error",userFormatterError,ctx);
        return;
    }
    await next();
}


const UserIsExist = async(ctx,next)=>{
    const res = await getUserInfo(ctx.request.body)
    if(res.length>0) {
        ctx.app.emit("error",userAlreadyExist,ctx);
        return;
    }
    console.log(res.length,"--length");
    await next();
}


const crptyPassword =async (ctx,next)=>{
    console.log("cry");
    const {password} = ctx.request.body;
    const salt = bcrypt.genSaltSync(10);
    const hash =bcrypt.hashSync(password,salt);
    console.log(hash,"hash--");
    ctx.request.body.password = hash;
    await next();
}


const verifyOldPwd = async (ctx,next)=>{
    const {oldPwd} = ctx.request.body;
    const res = await getUserInfo(ctx.request.body)
    if(res.length<=0) {
        ctx.app.emit("error",userNoExist,ctx);
        return;
    }else {
        const isTrue =  bcrypt.compareSync(oldPwd,res[0].password); // true
        if(!isTrue) {
            return ctx.app.emit("error",userPasswordFalse,ctx);
        }
        ctx.user = res[0];
    }
    await next();
}
module.exports = {UserValidate,UserIsExist,crptyPassword,verifyOldPwd}